// 代理配置的默认值
const DEFAULT_CONFIG = {
  host: 'localhost',
  port: 1080,
  username: '',
  password: ''
};

// 应用代理设置
async function applyProxySettings(enabled) {
  const { proxyConfig } = await chrome.storage.local.get('proxyConfig');
  const config = proxyConfig || DEFAULT_CONFIG;

  if (enabled) {
    const proxySettings = {
      mode: 'fixed_servers',
      rules: {
        singleProxy: {
          scheme: 'socks5',
          host: config.host,
          port: parseInt(config.port)
        },
        bypassList: ['localhost']
      }
    };

    if (config.username && config.password) {
      proxySettings.rules.singleProxy.username = config.username;
      proxySettings.rules.singleProxy.password = config.password;
    }

    await chrome.proxy.settings.set({
      value: proxySettings,
      scope: 'regular'
    });
  } else {
    // 禁用代理，使用系统设置
    await chrome.proxy.settings.set({
      value: { mode: 'system' },
      scope: 'regular'
    });
  }

  // 广播状态更新
  broadcastStatus(enabled, config);
}

// 广播代理状态更新
function broadcastStatus(enabled, config) {
  chrome.runtime.sendMessage({
    type: 'proxyStatusUpdate',
    enabled: enabled,
    config: config
  });
}

// 监听来自popup和options的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'updateProxyState') {
    (async () => {
      await chrome.storage.local.set({ proxyEnabled: message.enabled });
      await applyProxySettings(message.enabled);
      sendResponse({ success: true });
    })();
    return true;
  } else if (message.type === 'updateProxyConfig') {
    (async () => {
      await chrome.storage.local.set({ proxyConfig: message.config });
      await applyProxySettings(true);
      sendResponse({ success: true });
    })();
    return true;
  }
});

// 扩展安装时初始化配置
chrome.runtime.onInstalled.addListener(async () => {
  const { proxyEnabled, proxyConfig } = await chrome.storage.local.get(['proxyEnabled', 'proxyConfig']);
  if (proxyEnabled) {
    applyProxySettings(true);
  }
});

// 初始化时恢复之前的代理状态
chrome.runtime.onStartup.addListener(async () => {
  const { proxyEnabled } = await chrome.storage.local.get('proxyEnabled');
  if (proxyEnabled) {
    applyProxySettings(true);
  }
});